package com.kinyx.framework.processor;

import java.util.List;

import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;

/**
 * 工具类
 */
public final class Utils {

	/** 构造方法 */
	private Utils() {}

	/**
	 * 判断Element对象是标注了注解
	 * @param context 上下文环境
	 * @param element Element对象
	 * @param annotationName 注解名（全名）
	 * @return true：标注了注解；false：未标注注解；
	 */
	public static boolean containsAnnotation(final Context context, final Element element, final String annotationName) {
		// 取类中的注解
		final List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
		for (final AnnotationMirror annotationMirror : annotationMirrors) {
			if (annotationMirror.getAnnotationType().toString().equals(annotationName)) {
				context.getLogger().NOTE("Element[" + element + "] contains Annotation[" + annotationName + "]=true");
				return true;
			}
		}
		context.getLogger().NOTE("Element[" + element + "] contains Annotation[" + annotationName + "]=false");
		return false;
	}

	/**
	 * 判断Element对象是否是Class类型
	 * @param context 上下文环境
	 * @param element Element对象
	 * @return true：是Class类型；false：其它类型；
	 */
	public static boolean isClass(final Context context, final Element element) {
		final ElementKind kind = element.getKind();
		final boolean flag = ElementKind.CLASS.equals(kind);
		context.getLogger().NOTE("Element[" + element + "] ElementKind[" + kind.toString() + "] isClass[" + flag + "]");
		return flag;
	}

	/**
	 * 判断Element对象是否是Field类型
	 * @param context 上下文环境
	 * @param element Element对象
	 * @return true：是Field类型；false：其它类型；
	 */
	public static boolean isField(final Context context, final Element element) {
		final ElementKind kind = element.getKind();
		final boolean flag = ElementKind.FIELD.equals(kind);
		context.getLogger().NOTE("Element[" + element + "] ElementKind[" + kind.toString() + "] isField[" + flag + "]");
		return flag;
	}

	/**
	 * 取父类
	 * @param context 上下文环境
	 * @param typeElement 当前类
	 * @return 父类
	 */
	public static TypeElement getSuperclass(final Context context, final TypeElement typeElement) {
		final TypeMirror superClass = typeElement.getSuperclass();
		if ((superClass != null) && (superClass.getKind() == TypeKind.DECLARED)) {
			final TypeElement superclass = TypeElement.class.cast(DeclaredType.class.cast(superClass).asElement());
			context.getLogger().NOTE("class[" + typeElement + "] has super class[" + superClass + "]");
			return superclass;
		}
		context.getLogger().NOTE("class[" + typeElement + "] has no super class");
		return null;
	}

}
